package com.xinyue.auto.reader.process;

import org.dom4j.Element;

import com.xinyue.auto.annotation.Create;
import com.xinyue.auto.annotation.SetBoolean;
import com.xinyue.auto.annotation.SetNull;
import com.xinyue.auto.bean.MajorKey;
import com.xinyue.auto.exception.IdException;
import com.xinyue.auto.reader.Process;
import com.xinyue.auto.reader.major.AttributeMajor;
import com.xinyue.auto.reader.util.ColumnUtil;
import com.xinyue.auto.util.ArrayUtil;
import com.xinyue.auto.util.StringUtil;

public class IdProcess extends AttributeMajor{
	public IdProcess(Process read) {
		super(read);
	}
	
	@SetBoolean(false)
	private boolean autoKey;//是否是自动主键
	@SetNull
	private String start;//数据库支持的主键起始值
	@Create(MajorKey.class)
	private MajorKey key;//数据库表主键对象

	@Override
	protected void validate() throws Exception {
		//读取Id标签
		Element id = xml.element(id_);
		if(id == null) {
			throw new IdException("标签未定义", holder.getException());
		}
		
		//公共属性
		try {
			commonRead(id);
			
			anns.add("@Id");
			holder.getBeanImpt().add("javax.persistence.Id");
			
			//主键生成方式
			Element gv = id.element("generatedValue");
			String gt = null;
			if(gv != null) {
				gt = gv.attributeValue(value_);
				//读取数据库支持的主键起始值
				start = gv.attributeValue(start_);
			}else {
				gt = "IDENTITY";
			}
			
			if("IDENTITY".equals(gt)) {
				autoKey = true;
			}
			anns.add("@GeneratedValue(strategy=GenerationType." + gt + ")");
			
			holder.getBeanImpt().add("javax.persistence.GeneratedValue");
			holder.getBeanImpt().add("javax.persistence.GenerationType");
		} catch (Exception e) {
			throw new IdException(e.getMessage(), holder.getException());
		}
		
		//装配数据
		key.setName(name);
		key.setType(type);
		key.setDesc(desc);
		key.setStart(start);
		key.setAutoKey(autoKey);
		key.setAnnotations(ArrayUtil.toArray(anns));
	}

	@Override
	protected void install() {
		//将此属性添加至Entity对象中
		holder.getEntity().setId(key);
	}

	/**
	 * 读取ID标签上属性信息，并封装成JPA的注解类型
	 */
	@Override
	protected void columnAnn(Element prop) throws Exception{
		StringBuilder column = new StringBuilder();//column数据
		
		String t_name = ColumnUtil.compoundByName(column, prop, t_name_);//name：字段名
		String length = ColumnUtil.compound(column, prop, length_);//长度
		
		if(StringUtil.isNull(t_name)) {
			key.setDbName(name);
		}else {
			key.setDbName(t_name);
		}
		
		key.setType(type);//属性类型
		
		if(!StringUtil.isNull(length)) {
			key.setLength(length);
		}
		
		if(column.length() > 0) {
			String annc = "@Column(" + column.substring(2, column.length()) + ")";
			anns.add(annc);
			holder.getBeanImpt().add("javax.persistence.Column");
		}
	}
}